package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.Manufacturer;
import com.sskj.api.exception.LogicException;
import com.sskj.api.mapper.ManufacturerMapper;
import com.sskj.api.service.IManufacturerService;
import com.sskj.api.vo.req.ManufacturerPageListReq;
import com.sskj.common.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class ManufacturerService extends ServiceImpl<ManufacturerMapper, Manufacturer> implements IManufacturerService {

    @Override
    public void add(Manufacturer manufacturer) {
        LambdaQueryWrapper<Manufacturer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Manufacturer::getName, manufacturer);
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("厂商已存在");
        }

        manufacturer.setCreateTime(LocalDateTime.now());
        save(manufacturer);
    }

    @Override
    public void update(Manufacturer manufacturer) {
        LambdaQueryWrapper<Manufacturer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Manufacturer::getId, manufacturer.getId())
                .eq(Manufacturer::getName, manufacturer);
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("厂商已存在");
        }

        manufacturer.setUpdateTime(LocalDateTime.now());
        updateById(manufacturer);
    }

    @Override
    public IPage<Manufacturer> pageList(ManufacturerPageListReq req) {
        LambdaQueryWrapper<Manufacturer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Manufacturer::getId);
        if (StrUtil.isNotBlank(req.getName())) {
            lambdaQueryWrapper.like(Manufacturer::getName, req.getName());
        }
        if (req.getStatus() != null && req.getStatus() >= 0) {
            lambdaQueryWrapper.eq(Manufacturer::getStatus, req.getStatus());
        }

        IPage<Manufacturer> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        return page(pageConfig, lambdaQueryWrapper);
    }
}
